package com.cmcc.driver.ui.main


import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import androidx.fragment.app.Fragment
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProviders
import androidx.recyclerview.widget.LinearLayoutManager
import com.cmcc.driver.databinding.FragmentOrderInProgressBinding
import com.cmcc.driver.ui.dialog.AppProgressDialog
import com.cmcc.driver.ui.main.adapter.OrderInProgressAdapter
import com.cmcc.driver.ui.main.viewmodel.OrderProgressViewModel
import com.cmcc.shared.utils.DisplayUtil
import com.cmcc.shared.adapter.SpaceItemDecoration

/**
 * Author: jiangxin
 * Date: 2019/11/5
 * Description:
 */
class OrderInProgressFragment : Fragment() {

    private lateinit var binding: FragmentOrderInProgressBinding
    private var viewModel: OrderProgressViewModel? = null

    private var progressDialog: AppProgressDialog? = null

    private var adapter: OrderInProgressAdapter? = null


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        progressDialog = AppProgressDialog(context!!)

    }

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        binding = FragmentOrderInProgressBinding.inflate(inflater, container, false)

        viewModel = ViewModelProviders.of(this).get(OrderProgressViewModel::class.java)


        binding.recyclerView.layoutManager = LinearLayoutManager(activity)
        binding.recyclerView.addItemDecoration(
            SpaceItemDecoration(
                DisplayUtil.dp2px(
                    context!!,
                    20f
                ).toInt()
            )
        )
        adapter = OrderInProgressAdapter()
        adapter?.setActivity(activity)
        binding.recyclerView.adapter = adapter

        binding.swipeRefreshLayout.setOnRefreshListener {
            updateUI()
        }


        viewModel?.records?.observe(this, Observer { records ->
            binding.swipeRefreshLayout.isRefreshing = false

            adapter?.removeList()

            adapter?.addList(records.list)

            adapter?.notifyDataSetChanged()

            if (adapter?.itemCount == 0) {
                binding.noOrderLayout.visibility = View.VISIBLE
            } else {
                binding.noOrderLayout.visibility = View.GONE
            }
        })

        viewModel?.hasStatusChange()?.observe(this, Observer {
            if(it){
                updateUI()
            }
        })


        updateUI()


        return binding.root
    }


    fun updateUI() {
        viewModel?.getOrderListInProgress(0, 10)
    }


}